<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <a-form :form="form" slot="detail">
        <a-row>
          <a-col :span="12">
            <a-form-item label="组织名称" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="['name',validatorRules.tenantName]" placeholder="请输入组织全称"></a-input>
            </a-form-item>
          </a-col>

          <a-col :span="12">
            <a-form-item label="组织编码" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="['tenantCode',validatorRules.tenantCode]" placeholder="请输入组织编码"></a-input>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="12">
            <a-form-item label="统一社会信用代码" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="['socialCode',validatorRules.socialCode]" placeholder="统一社会信用代码"></a-input>
            </a-form-item>
          </a-col>

          <a-col :span="12">
            <a-form-item label="组织简称" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="['shortName', validatorRules.shortName]" placeholder="组织简称"></a-input>
            </a-form-item>
          </a-col>
        </a-row>

        <a-row>
          <a-col :span="12">
            <a-form-item label="组织地址" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="['address',validatorRules.address]" placeholder="组织地址"></a-input>
            </a-form-item>
          </a-col>

          <a-col :span="12">
            <a-form-item label="组织类型" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-dict-select-tag :triggerChange="true" v-decorator="[ 'type', validatorRules.type]" dictCode="CORP_TYPE"></j-dict-select-tag>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row>
<!--          <a-col :span="12">-->
<!--            <a-form-item label="状态" :labelCol="labelCol" :wrapperCol="wrapperCol">-->
<!--              <j-dict-select-tag :triggerChange="true" v-decorator="[ 'status', validatorRules.status]" dictCode="tenant_status"></j-dict-select-tag>-->
<!--            </a-form-item>-->
<!--          </a-col>-->
          <a-col :span="12">
            <a-form-item label="省份" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-select
                placeholder="请选择省份"
                optionFilterProp="children"
                :autoClearSearchValue="false"
                style="width: 100%"
                v-decorator="['province']"
                @change="changeProvince($event)"
                :getPopupContainer="(target) => target.parentNode">
                <a-select-option v-for="(item, index) in provinceList" :key="index" :value="item.areaCode">
                  {{ item.areaName }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="地市" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-select
                placeholder="请选择地市"
                optionFilterProp="children"
                :autoClearSearchValue="false"
                style="width: 100%"
                v-decorator="['city']"
                @change="changeCity($event)"
                :getPopupContainer="(target) => target.parentNode">
                <a-select-option v-for="(item, index) in cityList" :key="index" :value="item.areaCode">
                  {{ item.areaName }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="12">
            <a-form-item label="区县" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-select
                placeholder="请选择区县"
                optionFilterProp="children"
                :autoClearSearchValue="false"
                style="width: 100%"
                v-decorator="['county']"
                :getPopupContainer="(target) => target.parentNode">
                <a-select-option v-for="(item, index) in countyList" :key="index" :value="item.areaCode">
                  {{ item.areaName }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="联系人" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="['contactName',validatorRules.contactName]" placeholder="联系人"></a-input>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="12">
            <a-form-item label="联系人电话" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="['contactPhone',validatorRules.contactPhone]" placeholder="联系人电话"></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="组织邮箱" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="['email',validatorRules.email]" placeholder="组织邮箱"></a-input>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="12">
            <a-form-item label="组织网址" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="['url',validatorRules.url]" placeholder="组织网址"></a-input>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col v-if="showFlowSubmitButton" :span="24" style="text-align: center">
            <a-button @click="submitForm">提 交</a-button>
          </a-col>
        </a-row>
      </a-form>
    </j-form-container>
  </a-spin>
</template>

<script>

  import { queryById, addTenant, editTenant, listAreaByLevel } from '../service'
  import { refreshDictCache, queryDictItems } from '../../sysConfig/dict/service'
  import pick from 'lodash.pick'
  import JFormContainer from '@/components/jeecg/JFormContainer'
  import JDictSelectTag from '@/components/dict/JDictSelectTag'
  import { UI_CACHE_DB_DICT_DATA } from '@/store/mutation-types'
  import Vue from 'vue'
  import { duplicateCheck } from '@api/api';

  export default {
    name: 'TenantForm',
    components: {
      JFormContainer,
      JDictSelectTag
    },
    props: {
      formData: {
        type: Object,
        default: () => {},
        required: false
      },
      normal: {
        type: Boolean,
        default: false,
        required: false
      },
      disabled: {
        type: Boolean,
        default: false,
        required: false
      }
    },
    data () {
      return {
        form: this.$form.createForm(this),
        provinceList: [],
        cityList: [],
        countyList: [],
        model: {},
        labelCol: {
          xs: { span: 24 },
          sm: { span: 8 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 }
        },
        confirmLoading: false,
        url: {
        },
        validatorRules: {
          tenantName: { rules: [{ required: true, message: '请输入组织全称' }, { validator: this.validateTenantName }] },
          tenantCode: { rules: [{ validator: this.validateTenantCode }] },
          socialCode: { rules: [{ validator: this.validateSocialCode }] },
          shortName: { rules: [{ validator: this.validateShortName }] },
          address: { rules: [{ required: true, message: '请输入组织地址' }, { validator: this.validateAddress }] },
          type: { rules: [{ required: true, message: '请选择组织类型' }] },
          contactName: { rules: [{ validator: this.validateContactName }] },
          contactPhone: { rules: [{ validator: this.validatePhone }] },
          email: { rules: [{ validator: this.validateEmail }] },
          url: { rules: [{ validator: this.validateUrl }] }
        }
      }
    },
    computed: {
      formDisabled() {
        if (this.normal === false) {
          if (this.formData.disabled === false) {
            return false
          } else {
            return true
          }
        }
        return this.disabled
      },
      showFlowSubmitButton() {
        if (this.normal === false) {
          if (this.formData.disabled === false) {
            return true
          } else {
            return false
          }
        } else {
          return false
        }
      }
    },
    created () {
      this.showFlowData();
    },
    methods: {
      add () {
        this.edit({ status: 1 });
      },
      addSub (record) {
        this.edit({ parentId: record.id });
      },
      edit (record) {
        this.form.resetFields();
        this.provinceList = [];
        this.cityList = [];
        this.countyList = [];
        this.visible = true;
        this.model = Object.assign({}, record);
        if (this.model.id) {
          this.initProvince(1);
          if (this.model.province) {
            this.initCity(2, this.model.province);
          }
          if (this.model.city) {
            this.initCounty(3, this.model.city);
          }
          this.$nextTick(() => {
            this.form.setFieldsValue(pick(this.model, 'tenantCode', 'socialCode', 'name', 'shortName', 'address', 'type', 'province', 'city', 'county', 'contactName', 'contactPhone', 'email', 'url'))
          })
        } else {
          this.initProvince(1);
        }
      },
      showFlowData() {
        if (this.normal === false) {
          let id = this.formData.dataId;
          queryById(id).then((res) => {
            if (res.success) {
              this.edit(res.result);
            }
          });
        }
      },
      submitForm () {
        const that = this;
        // 触发表单验证
        this.form.validateFields((err, values) => {
          if (!err) {
            that.confirmLoading = true;
            let formData = Object.assign(this.model, values);
            formData.status = 1;
            console.log('表单提交数据', formData)
            let obj
            if (!this.model.id) {
              obj = addTenant(formData)
            } else {
              obj = editTenant(formData)
            }
            obj.then((res) => {
              if (res.success) {
                that.$message.success(res.message);
                that.refreshCache();
                that.$emit('ok');
              } else {
                if (res.message === '该编号已存在!') {
                  this.model.id = ''
                }
                that.$message.warning(res.message);
              }
            }).finally(() => {
              that.confirmLoading = false;
            })
          }
        })
      },
      refreshCache() {
        refreshDictCache().then((res) => {
          if (res.success) {
            // 重新加载缓存
            queryDictItems().then((res) => {
              if (res.success) {
                Vue.ls.remove(UI_CACHE_DB_DICT_DATA)
                Vue.ls.set(UI_CACHE_DB_DICT_DATA, res.result, 7 * 24 * 60 * 60 * 1000)
              }
            })
          }
        })
      },
      validateTenantName(rule, value, callback) {
        if (!value) {
          callback();
        } else {
          if (value.length < 51) {
            var params = {
              tableName: 'sys_tenant',
              fieldName: 'name',
              fieldVal: value,
              dataId: this.model.id,
              delFlag: 'del_flag',
              delFlagValue: 0
            };
            duplicateCheck(params).then((res) => {
              if (res.success) {
                callback()
              } else {
                callback('租户名称已存在!')
              }
            })
          } else {
            callback('租户名称长度不大于50个字符!')
          }
        }
      },
      validateTenantCode(rule, value, callback) {
        if (!value) {
          callback();
        } else {
          if (value.length < 51) {
            var params = {
              tableName: 'sys_tenant',
              fieldName: 'tenant_code',
              fieldVal: value,
              dataId: this.model.id,
              delFlag: 'del_flag',
              delFlagValue: 0
            };
            duplicateCheck(params).then((res) => {
              if (res.success) {
                callback()
              } else {
                callback('租户编码已存在!')
              }
            })
          }else {
            callback('租户编码长度不大于50个字符!')
          }
        }
      },
      validateSocialCode(rule, value, callback) {
        if (!value) {
          callback();
        } else {
          if (this.isValidUSCI(value)) {
            var params = {
              tableName: 'sys_tenant',
              fieldName: 'social_code',
              fieldVal: value,
              dataId: this.model.id,
              delFlag: 'del_flag',
              delFlagValue: 0
            };
            duplicateCheck(params).then((res) => {
              if (res.success) {
                callback()
              } else {
                callback('统一社会信用代码已存在!')
              }
            })
          } else {
            callback('请输入正确格式的统一社会信用代码!')
          }
        }
      },
      validatePhone(rule, value, callback) {
        if (!value) {
          callback()
        } else {
          if (new RegExp(/^1[3|4|5|7|8|9][0-9]\d{8}$/).test(value)) {
            callback();
          } else {
            callback('请输入正确格式的手机号码!');
          }
        }
      },
      validateEmail(rule, value, callback) {
        if (!value) {
          callback()
        } else {
          if (value.length < 51) {
            if (new RegExp(/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/).test(value)) {
              callback()
            } else {
              callback('请输入正确格式的邮箱!')
            }
          } else {
            callback('邮箱的长度不能大于50个字符!')
          }
        }
      },
      validateAddress(rule, value, callback) {
        if (!value) {
          callback()
        } else {
          if (value.length < 256) {
            callback()
          } else {
            callback('地址长度不能大于256个字符!')
          }
        }
      },
      validateShortName(rule, value, callback) {
        if (!value) {
          callback()
        } else {
          if (value.length < 51) {
            callback()
          } else {
            callback('租户简称不能大于50个字符!')
          }
        }
      },
      validateContactName(rule, value, callback) {
        if (!value) {
          callback()
        } else {
          if (value.length < 21) {
            callback()
          } else {
            callback('联系人不能大于20个字符!')
          }
        }
      },
      validateUrl(rule, value, callback) {
        if (!value) {
          callback()
        } else {
          if (value.length < 51) {
            callback()
          } else {
            callback('组织网址不能大于50个字符!')
          }
        }
      },
      changeProvince(provinceCode) {
        this.cityList = [];
        this.countyList = [];
        this.initCity(2, provinceCode);
        this.form.resetFields('city', '');
        this.form.resetFields('county', '');
      },
      changeCity(cityCode) {
        this.countyList = [];
        this.initCounty(3, cityCode);
        this.form.resetFields('city', '');
        this.form.resetFields('county', '');
      },
      initProvince(level) {
        listAreaByLevel({ level: level }).then(res => {
          if (res.success) {
            this.provinceList = res.result
          }
        })
      },
      initCity(level, parentCode) {
        listAreaByLevel({ level: level, parentCode: parentCode }).then(res => {
          if (res.success) {
            this.cityList = res.result
          }
        })
      },
      initCounty(level, parentCode) {
        listAreaByLevel({ level: level, parentCode: parentCode }).then(res => {
          if (res.success) {
            this.countyList = res.result;
          }
        })
      },
      /**
       * @description           根据GB 32100—2015法人和其他组织统一社会信用代码编码规则，校验该字符串是否为正确的统一社会信用代码
       * @param {string} usci   统一社会信用代码
       * @returns {boolean}     boolean 验证结果，是否为符合规则的统一社会信用代码
       */
      isValidUSCI(usci) {
        if (typeof usci !== 'string') return false;
        usci = usci.trim();
        // 标准规定的要18位
        if (usci.length !== 18) return false;
        /** 代码-值对应，以此得出C_i */
        const map = new Map();
        map.set('0', 0);
        map.set('1', 1);
        map.set('2', 2);
        map.set('3', 3);
        map.set('4', 4);
        map.set('5', 5);
        map.set('6', 6);
        map.set('7', 7);
        map.set('8', 8);
        map.set('9', 9);
        map.set('A', 10);
        map.set('B', 11);
        map.set('C', 12);
        map.set('D', 13);
        map.set('E', 14);
        map.set('F', 15);
        map.set('G', 16);
        map.set('H', 17);
        map.set('J', 18);
        map.set('K', 19);
        map.set('L', 20);
        map.set('M', 21);
        map.set('N', 22);
        map.set('P', 23);
        map.set('Q', 24);
        map.set('R', 25);
        map.set('T', 26);
        map.set('U', 27);
        map.set('W', 28);
        map.set('X', 29);
        map.set('Y', 30);

        /** 根据公式计算Ci * Wi的值的列表，总共17个值，以此来计算第18个值 */
        const list = new Array(17).fill(0);
        for (let i = 0; i < 17; i++) {
          const C = map.get(usci[i]);
          // 不在序列里的话，直接返回false
          if (isNaN(C)) return false;
          const W = Math.pow(3, i) % 31;
          list[i] = C * W;
        }
        // 计算级数之和
        const sum = list.reduce((prev, curr) => prev + curr);
        // 求出校验码字符值
        let C_18 = 31 - (sum % 31);
        if (C_18 === 31) {
          C_18 = 0;
        }
        // 根据校验码字符值，根据map，得到第18位的字符
        let val18 = null;
        for (let [key, value] of map.entries()) {
          if (value === C_18) {
            val18 = key;
          }
        }
        return val18 === usci[17];
      }
    }
  }
</script>
